#pragma once
#include <iostream>
#include <memory>
#include <unordered_map>
#include "Epoller.hpp"
#include "Connection.hpp"
class EpollServer
{
    const static int _revs_num = 64;
public:
    EpollServer():_ep_server(std::make_unique<Epoller>()),_is_running(false)
    {
    }
    void Init()
    {
        _ep_server->Init();
    }
    void InsertConnection(int sockfd,connection_t& conn)
    {
        if(_connections.find(sockfd)!=_connections.end())
        {
            _connections.insert(std::make_pair(sockfd,conn));
        }
        //将节点放入红黑树
        struct epoll_event ev;
        ev.data.fd = sockfd;
        ev.events = EPOLLIN;
        _ep_server->CTL(EPOLL_CTL_ADD,sockfd,&ev);
    }
    void Loop()
    {
        _is_running = true;
        while(_is_running)
        {
            int n = _ep_server->Wait(_revs,_revs_num);
            //有错误
            for(int i = 0;i<n;i++)
            {
                _connections[_revs[i].data.fd]->Recv();
            }
        }
        _is_running = false;

    }
    ~EpollServer()
    {

    }
private:
    std::unique_ptr<Epoller> _ep_server;
    std::unordered_map<int,connection_t> _connections;
    struct epoll_event _revs[_revs_num];
    bool _is_running;
};